package com.ziwei.material.service.impl;

import com.ziwei.material.domain.po.SdsMaterialTaskPic;
import com.ziwei.material.service.MaterialTaskDownloadService;
import com.ziwei.material.service.MaterialTaskPicService;
import com.ziwei.material.service.MaterialTaskService;
import com.ziwei.material.util.AliOssUtil;
import com.ziwei.material.util.FileUtils;
import com.ziwei.material.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.UUID;

/**
 * @Author: 彭于晏福建分晏
 * @Description: TODO
 * @DateTime: 2024/11/17 11:43
 **/
@Service
public class MaterialTaskDownloadServiceImpl implements MaterialTaskDownloadService {



    @Resource
    private MaterialTaskService materialTaskService;

    @Resource
    private MaterialTaskPicService materialTaskPicService;


    @Override
    public void downloadImage(List<SdsMaterialTaskPic> list, Long taskId) {
        int downloadNum = 0;




        //处理文件
        for (SdsMaterialTaskPic sdsMaterialTaskPic : list) {
            String url = sdsMaterialTaskPic.getPicUrl();

            if (!FileUtils.isValidImageUrl(url)){
                sdsMaterialTaskPic.setAnalyseRes(1);  //下载失败
                sdsMaterialTaskPic.setStatus(1);  //不可用
                continue;
            }


            //上传文件
            try(InputStream inputStream = new URL(url).openStream()){
                String objectName = getNewUrlName();

                String ossUrl = AliOssUtil.uploadImage(objectName, inputStream);

                System.out.println("上传文件路径:" + ossUrl);

                sdsMaterialTaskPic.setOssUrl(ossUrl);

                downloadNum++;
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        //批量更新任务图片表状态
        materialTaskPicService.updateBatchById(list);

        //统计分析结果为0的图片数量,如果数量为0,代表全部下载失败,任务结束
        long zeroCount = list.stream()
                .filter(pic -> pic.getAnalyseRes() == 0)
                .count();


        if (zeroCount == 0){
            materialTaskService.updateTaskAllFailDownloadCondition(taskId);
        }else {
            //更新任务表状态
            materialTaskService.updateTaskDownloadCondition(downloadNum, taskId);
        }









    }

    //生成随机图片名字
    public static String getNewUrlName(){
        String suffixName = ".jpg";

        String uuid = UUID.randomUUID().toString();

        String originData = System.currentTimeMillis() + "-" + uuid;

        String md5Hash = StringUtil.getMd5(originData);

        return md5Hash + suffixName;


    }

}
